# This code is hosted on http://code.google.com/p/lenthorp/
# Freely available for use in applications, but should NOT be modified
# Email all comments to lenthorpresearch@gmail.com

from PricingEngine_HullWhiteMod import *
from CalibratorMod import *

import Settings
mainLocation = Settings.mainLocation
MySQLUsername = Settings.MySQLUsername
import MySQLdb

ccy = 'usd'
marketdb = MySQLdb.connect("localhost",MySQLUsername,'',"marketData" )
marketc = marketdb.cursor()
marketc.execute('SELECT Tenor, Rate FROM ' + ccy + 'zerorates')
    
def runTest():
    # Get test data
    data = marketc.fetchall()
    tenors = []
    rates = []
    for row in data:
        tenors.append(row[0])
        rates.append(row[1])
    zeroRates = {'tenors' : tenors, 'rates' : rates}

    mp = ModelParameters()
    mp.p['zeroRates'] = zeroRates
    hwe = HullWhite(mp)
    op = OptimiseParameters()
    op.p['nu'] = 0.00481
    op.p['lambda'] = 0.01035
    pp = PricingParameters(['swaptionMaturity', 'swapTenor', 'fwdSwapRate'])
    marketc.execute('SELECT SwaptionMaturity, SwapTenor, SwaptionVolatility, ForwardSwapRate FROM ' + ccy + 'swaptionvolatilities')
    data = marketc.fetchall()
    for row in data:
        sm = row[0]
        st = row[1]
        fs = row[3]
        if sm + st > 29.9 and sm + st < 31.1:
            weight = 1.0
        else:
            weight = 0.0
        pp.addPricingSet([sm,st,fs],row[2],weight)
    marketdb.close()

    # Do the calibration
    dm = SumOfSquaresDistance()
    hwe.setUpParameters(pp,op)
    cb = ScipyFminBFGSCalibrator(hwe, pp, op, dm)
    ##print(cb.calibrate())
    res = hwe.getPrice()
    return res
    
if __name__ == "__main__":
    res = runTest()
    print(res)